import pgzrun
import random
import json
import os
import tkinter as tk
import _thread
from tkinter.filedialog import *

ROWS = 100
COLS = 150
CELL_SIZE = 7
IS_STOP=True
STEP=0

HEIGHT = (ROWS * CELL_SIZE)
WIDTH  = (COLS * CELL_SIZE + 90)

BACK_COLOR = (0, 0, 50)

def GenCellColor():
    return [random.randint(0, 50), random.randint(175, 250), random.randint(50, 100)]

def init_map(rows, cols):
    return [[[0, BACK_COLOR] for c in range(cols)] for r in range(rows)]

def clear():
    global world
    world=init_map(ROWS,COLS)

def count_neighbors(w, r, c):
    sum = 0
    clr = [0, 0, 0]
    for nr in range(r - 1, r + 1 + 1):
        for nc in range(c - 1, c + 1 + 1):
            mr=nr
            mc=nc
            
            if nr == r and nc == c:
                continue
            
            if nr < 0:
                mr = ROWS-1
            if nr >= ROWS:
                mr = 0
            
            if nc < 0:
                mc = COLS-1
            if nc >= COLS:
                mc = 0

            if w[mr][mc][0]:
                sum += 1
                clr[0] += w[mr][mc][1][0]
                clr[1] += w[mr][mc][1][1]
                clr[2] += w[mr][mc][1][2]
    if sum == 0:
        return sum, clr
    else:
        return sum, [clr[0] // sum, clr[1] // sum, clr[2] // sum]

def next_cell(w, r, c):
    n, clr = count_neighbors(w, r, c)

    if n == 3:
        return [1, clr]
    elif n == 2:
        return w[r][c]
    else:
        return [0, BACK_COLOR]

def save():
    files=os.listdir(".")
    x=0
    name=""
    while True:
        name="LifeGameMap"+str(x)+".json"
        if name not in files:
            break
        x+=1
    os.mknod(name)
    f=open(name,'w')
    f.write('{"size":['+str(ROWS)+','+str(COLS)+','+str(CELL_SIZE)+"],\n")
    f.write('"map":[\n')
    n=[]
    for i in range(len(world)):
        for j in range(len(world[i])):
            if not world[i][j][0]:
                continue
            o=("["+str(i)+','+str(j)+']')
            n.append(o)
    for i in range(len(n)):
        f.write(n[i])
        if i!=len(n)-1:
            f.write(',')
    f.write(']}')
        
    f.close()

world = init_map(ROWS, COLS)
next_world = init_map(ROWS, COLS)
on=[0,0]

def get_cells(world):
    x=0
    for i in range(ROWS):
        for j in range(COLS):
            x+=world[i][j][0]
    return x

def on_key_down(key):
    global world,IS_STOP,STEP
    if key==keys.DELETE:
        world=init_map(ROWS,COLS)
    if key==keys.END:
        save()
    if key==keys.SPACE:
        IS_STOP=not IS_STOP
        print('go')
    if key==keys.C:
        STEP=0

def on_mouse_down(pos):
    global world
    x=pos[1]//CELL_SIZE
    y=pos[0]//CELL_SIZE
    if y>=COLS:
        return
#    print(x,y)
    world[x][y]=[int(not world[x][y][0]),GenCellColor()]

def on_mouse_move(pos):
    global on
    x=pos[1]//CELL_SIZE
    y=pos[0]//CELL_SIZE
    if y>COLS:
        return
    on=[x,y]

def draw_cell(w, r, c):
    cx = CELL_SIZE * c
    cy = CELL_SIZE * r
    cell_rect = Rect((cx, cy), (CELL_SIZE, CELL_SIZE))
    screen.draw.filled_rect(cell_rect, tuple(w[r][c][1]))

def draw_line(w, r, c):
    cx = CELL_SIZE * c
    cy = CELL_SIZE * r
    line_rect = Rect((cx, cy), (CELL_SIZE+1, CELL_SIZE+1))
    screen.draw.rect(line_rect, (150,150,150))

def update():
    global STEP
    if IS_STOP:
        return
    STEP+=1
    for r in range(ROWS):
        for c in range(COLS):
            next_world[r][c] = next_cell(world, r, c)
    
    for r in range(ROWS):
        for c in range(COLS):
            world[r][c] = next_world[r][c]

def draw():
    screen.fill(tuple(BACK_COLOR))
    for r in range(ROWS):
        for c in range(COLS):
            if world[r][c][0]:
                draw_cell(world, r, c)
    for i in range(0,WIDTH-89,CELL_SIZE):
        screen.draw.line((i,0),(i,HEIGHT),(150,150,150))
    for i in range(0,HEIGHT,CELL_SIZE):
        screen.draw.line((0,i),(WIDTH-90,i),(150,150,150))
    main_point=WIDTH-45
    point=HEIGHT
    screen.draw.text(('x:'+str(on[1]).zfill(3)), midtop=(main_point-20,10))
    screen.draw.text(('y:'+str(on[0]).zfill(2)), midtop=(main_point-25,30))
    n=get_cells(world)
    screen.draw.text(('cells:'+str(n).zfill(5)), midtop=(main_point+2,50))
    screen.draw.text((str(STEP).zfill(6))+'step', midtop=(main_point+2,70))
    screen.draw.text('Use space', midtop=(main_point+2,point-128))
    screen.draw.text('to start  ', midtop=(main_point+2,point-108))
    screen.draw.text('Use delete', midtop=(main_point+2,point-88))
    screen.draw.text('to clear  ', midtop=(main_point+2,point-68))
    screen.draw.text('Use end to', midtop=(main_point+2,point-48))
    screen.draw.text('save file ', midtop=(main_point+2,point-28))

def tktk():
    top=tk.Tk()
    top.title("LifeGameEditor")
    top.resizable(False,False)
    
    frame1=tk.Frame(top)
    frame1.pack()
    rowlb=tk.Label(frame1,text='row:')
    rowsp=tk.Spinbox(frame1, from_=1, to=100, width=5)
    rowlb.pack(side=tk.LEFT)
    rowsp.pack(side=tk.LEFT)
    
    frame2=tk.Frame(top)
    frame2.pack()
    collb=tk.Label(frame2,text='col:')
    colsp=tk.Spinbox(frame2, from_=1, to=150, width=5)
    collb.pack(side=tk.LEFT)
    colsp.pack(side=tk.LEFT)
           
    def SelectFile():
        filepath = askopenfilename(filetypes=[('JSON','.json')])
        filename=tk.StringVar()
        filename.set(filepath)
        return filename
    
    def create():
        global CELL_SIZE,ROWS,COLS,WIDTH,HEIGHT,world
        ROWS=int(rowsp.get())
        COLS=int(colsp.get())
        if COLS>=ROWS:
            CELL_SIZE=int(150/COLS*4.75)
        else:
            CELL_SIZE=int(150/ROWS*4.75)
        HEIGHT = (ROWS * CELL_SIZE)
        WIDTH  = (COLS * CELL_SIZE + 90)
        world=init_map(ROWS,COLS)
    
    def load():
        global CELL_SIZE,ROWS,COLS,WIDTH,HEIGHT,world
        ftext=''
        name=SelectFile()
        name=name.get()
        try:
            with open(file = name, mode = 'r', encoding = 'utf8') as f:
                ftext = f.read()
            print('great')
        except:
            return
        data = json.loads(ftext)
        ROWS = data["size"][0]
        COLS = data["size"][1]
        CELL_SIZE = data["size"][2]
        HEIGHT = (ROWS * CELL_SIZE)
        WIDTH  = (COLS * CELL_SIZE+90)
        world=init_map(ROWS,COLS)
        for i in data['map']:
            world[i[0]][i[1]] = [1, GenCellColor()]
    
    frame4=tk.Frame(top)
    frame4.pack()
    btnc=tk.Button(frame4,text='create',command=create)
    btnc.pack()
    
    frame5=tk.Frame(top)
    frame5.pack()
    btnl=tk.Button(frame5,text='load',command=load)
    btnl.pack()
    
    frame6=tk.Frame(top)
    frame6.pack()
    btns=tk.Button(frame6,text='save',command=save)
    btns.pack()
    
    frame7=tk.Frame(top)
    frame7.pack()
    btns=tk.Button(frame6,text='clear',command=clear)
    btns.pack()
    
    top.mainloop()

_thread.start_new_thread(tktk,())
pgzrun.go()